package com.ykdl.member.kid.marketcard;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import oauth.signpost.http.HttpParameters;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sitech.oncon.barcode.core.CaptureActivity;
import com.ykdl.member.constant.China;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.DistanceAdapter;
import com.ykdl.member.kid.adapters.DistanceAdapterTo;
import com.ykdl.member.kid.beans.StoreBean;
import com.ykdl.member.kid.beans.StoreInfoJsonBean;
import com.ykdl.member.kid.beans.Store_ListBean;
import com.ykdl.member.kid.beans.TopicAndPostBean;
import com.ykdl.member.kid.beans.TopicBean;
import com.ykdl.member.kid.doctor.ActionsDoctorOnlineActivity;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.util.LocationUtils;
import com.ykdl.member.kid.util.LocationUtils.onLocationChangeListener;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class NearbyCardActivity extends BaseScreen {

	private RefreshListView card_list;
	private CarLlistAdapter adapter;
	private DistanceAdapter distance_adapter;
	private DistanceAdapterTo distance_adapter_to;
	private LocationManager lm;
	private StringBuilder sb;
//	public LocationClient mLocationClient = null;
//	public BDLocationListener myListener = new MyLocationListener();
	private boolean isfirst = true;
	private int start_id = 0;
	private int cursor = 0;
	private int count = 8;
	private int idx;
	private String coordinate_x="";
	private String coordinate_y;
	private LinearLayout ll_distance, ll_area;
	private TextView sort, city;
	private View view01, view02;
	private int screenWidth;
	private int screenHeight;
	private ArrayList<StoreInfoJsonBean> store_list = new ArrayList<StoreInfoJsonBean>();
	private boolean issetleftlist = false;
	private LinearLayout ll_layout;
	private String City;
	private String area;
	private boolean isShowDialog=true;
	private boolean isFilter=false;
	private boolean isLocation=true;
	private RelativeLayout gone_layout;
	private TextView tv_error_text;
	private LinearLayout all_content;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTopTitle("附近的门店卡", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {

				finish();
			}
		}, 0, 0, null, R.drawable.title_bg, false);
		setContent(R.layout.nearbycardactivity_xml);
		inint();
	//	inintLocationClient();
		initLocation();
	}
//	public void inintLocationClient() {
//		mLocationClient = new LocationClient(getApplicationContext()); // 声明LocationClient类
//		mLocationClient.setAccessKey("s1eKKY86UXHuviv3A7sSrWOW");
//		mLocationClient.registerLocationListener(myListener); // 注册监听函数
//		setLocationOption();
//		showProgress("正在加载中,请稍等...");
//		mLocationClient.start();// 开始定位
//		
//	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		store_list = new ArrayList<StoreInfoJsonBean>();
		isfirst = true;

	}

	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		mLocationUtils.stop();
	}

	public void inint() {
		isfirst = true;
		initScreenWidth();
		ll_layout = (LinearLayout) findViewById(R.id.ll_layout);
		ll_distance = (LinearLayout) findViewById(R.id.ll_all);
		ll_area = (LinearLayout) findViewById(R.id.ll_location);
		sort = (TextView) findViewById(R.id.sort);
		city = (TextView) findViewById(R.id.city);
		view01 = findViewById(R.id.view01);
		view02 = findViewById(R.id.view02);
		gone_layout=(RelativeLayout) findViewById(R.id.error_view);
		tv_error_text=(TextView) findViewById(R.id.tv_error_text);
		card_list = (RefreshListView) findViewById(R.id.card_list);
		all_content=(LinearLayout) findViewById(R.id.all_content);
		ll_distance.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sort.setTextColor(Color.parseColor("#CD8162"));
				view01.setVisibility(View.VISIBLE);
				city.setTextColor(Color.parseColor("#ADADAD"));
				view02.setVisibility(View.INVISIBLE);
				idx = 1;
				count = 20;
				cursor = 0;
				store_list = new ArrayList<StoreInfoJsonBean>();
				isFilter=false;
				isfirst = true;
				isLocation=true;
				isShowDialog=true;
			//	inintLocationClient();
				// showPopupWindow(findViewById(R.id.ll_layout), 1);
				initLocation();
			}
		});
		ll_area.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sort.setTextColor(Color.parseColor("#ADADAD"));
				view01.setVisibility(View.INVISIBLE);
				city.setTextColor(Color.parseColor("#CD8162"));
				view02.setVisibility(View.VISIBLE);
				idx = 2;
				count = 20;
				cursor = 0;
				isShowDialog=true;
				store_list = new ArrayList<StoreInfoJsonBean>();
				showPopupWindow(findViewById(R.id.ll_layout), 2);
			}
		});

		
		findViewById(R.id.go_ad).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				go(CaptureActivity.class, "isShow", false);
			}
		});
		card_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				StoreInfoJsonBean bean = (StoreInfoJsonBean) adapter.getItem(arg2);
				Intent intent = new Intent(NearbyCardActivity.this,
						CardInfoActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.putExtra(KidAction.STORE_ID, bean.getStore_id()+"");
				intent.putExtra("from","false");
				NearbyCardActivity.this.startActivity(intent);
			}
		});
		card_list.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				isShowDialog=false;
				issetleftlist = false;
				store_list = new ArrayList<StoreInfoJsonBean>();
				count = 20;
				cursor = 0;
				getData();
			}
		});
		card_list.setMoreClick(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				isShowDialog=false;
				issetleftlist = true;
				count = 20;
				getData();
			}
		});
		adapter = new CarLlistAdapter();
	}

	private ListView lv1, lv2;
	RelativeLayout lv2_layout;
	

	public void showPopupWindow(View anchor, int flag) {
		final PopupWindow popupWindow = new PopupWindow(NearbyCardActivity.this);
		View contentView = LayoutInflater.from(NearbyCardActivity.this)
				.inflate(R.layout.windows_popupwindow, null);
		lv1 = (ListView) contentView.findViewById(R.id.lv1);
		lv2 = (ListView) contentView.findViewById(R.id.lv2);
		lv1.setDivider(null);lv2.setDivider(null);
		lv2_layout = (RelativeLayout) contentView.findViewById(R.id.lv2_layout);

		switch (flag) {
		case 1:
			break;
		case 2:
			distance_adapter = new DistanceAdapter(NearbyCardActivity.this,
					initLv1Data());
			lv1.setAdapter(distance_adapter);
			distance_adapter.notifyDataSetChanged();
			break;
		}
		popupWindow.setWidth(screenWidth);
		popupWindow.setHeight(screenHeight / 2);
		popupWindow.setContentView(contentView);
		popupWindow.setFocusable(true);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new PaintDrawable());
		popupWindow.showAsDropDown(anchor);
		popupWindow.update();
//一级菜单
		lv1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (lv2_layout.getVisibility() == View.GONE) {
					lv2_layout.setVisibility(View.VISIBLE);
				}

				switch (idx) {
				case 1:
					distance_adapter_to = new DistanceAdapterTo(
							NearbyCardActivity.this, initLv2Data(position));

					lv2.setAdapter(distance_adapter_to);
					distance_adapter_to.notifyDataSetChanged();
					break;
				case 2:
					Log.i("idx", idx + "");
					distance_adapter_to = new DistanceAdapterTo(
							NearbyCardActivity.this, initLv2Data(position));
					Log.i("position", position + "");
					lv2.setAdapter(distance_adapter_to);
					distance_adapter_to.notifyDataSetChanged();
					break;
				}
				City=(String)parent.getAdapter().getItem(position);
				distance_adapter.setSelectItem(position);
				distance_adapter.notifyDataSetChanged();
			}
		});
//二级菜单
		lv2.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String name = (String) parent.getAdapter().getItem(position);
				try {
					area = URLEncoder.encode(City+","+name, "utf8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				isFilter=true;
				popupWindow.dismiss();
				getData();
			}
		});
	}

	private void initScreenWidth() {
		DisplayMetrics dm = new DisplayMetrics();
		dm = getResources().getDisplayMetrics();
		screenHeight = dm.heightPixels;
		screenWidth = dm.widthPixels;
		Log.v("屏幕宽高", "宽度" + screenWidth + "高度" + screenHeight);
	}

	private List<String> initLv1Data() {
		ArrayList<String> l = new ArrayList<String>();
		for (int i = 0; i < China.states.length - 1; i++) {
			l.add(China.states[i]);
		}
		return l;
	}

	private List<String> initLv2Data(int number) {
		List<String> l = new ArrayList<String>();
		for (int i = 0; i < China.counties[number].length; i++) {
			l.add(China.counties[number][i]);
		}
		return l;
	}

	public void getData() {
		String pageurl = "";
		HttpParameters parameterss = new HttpParameters();
		parameterss.put("coordinate_x", coordinate_x);
		parameterss.put("coordinate_y", coordinate_y);
		if (isShowDialog) {
			showProgress("正在加载中,请稍等...");
		}
		if (isFilter) {
			pageurl = KidConfig.GET_STOR_LIST;
			parameterss.put("area", area);
		} else {
			pageurl = KidConfig.GET_NEARLY;
			
		}
		parameterss.put("start_id", String.valueOf(start_id));
		parameterss.put("cursor", String.valueOf(cursor));
		parameterss.put("count", String.valueOf(count));
		if (isfirst) {
			store_list= new ArrayList<StoreInfoJsonBean>();
			adapter.setList(store_list);
			card_list.setAdapter(adapter);
			adapter.notifyDataSetChanged();
		}
		isfirst = false;
		HttpBaseRequest request = Wxxr.getInstance().postBaseRequest(pageurl,
				parameterss, null);
		TaskManager.startHttpRequest(request, new getDataTag(),
				Store_ListBean.class);
	}

	class getDataTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof Store_ListBean) {
				Store_ListBean bean = (Store_ListBean) t;
				ArrayList<StoreInfoJsonBean>  stores;
				if (isFilter) {
					stores=bean.getStores();
				}else {
					stores=bean.getStore_list();
				}
				if(stores.size()==0){
					showErrorView(true, "您所选城市暂无门店");
				}else{
					showErrorView(false, "");
				}
				if (null != stores) {
					int index = 0;
					if (store_list.size() > 1) {
						index = store_list.size() - 1;
					}
					for (StoreInfoJsonBean obj : stores) {
						store_list.add(obj);
					}
					adapter.setList(store_list);
					
					card_list.setAdapter(adapter);
					adapter.notifyDataSetChanged();
					if (bean.getNext_cursor() == bean.getTotal_number()) {
						card_list.setMoreButtoIsGon(true);
					} else {
						cursor = bean.getNext_cursor(); 
						card_list.setMoreButtoIsGon(false);
					}
					if (issetleftlist) {
						card_list.setSelection(index);
					}
					card_list.onRefreshComplete();
					card_list.setFecthMoreOk();
				}

			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			showErrorView(true, "您所选城市暂无门店");
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub

		}

	}

	class CarLlistAdapter extends BaseAdapter {

		ArrayList<StoreInfoJsonBean> list;

		public void setList(ArrayList<StoreInfoJsonBean> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (list != null) {
				return list.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if (getCount() != 0) {
				return list.get(position - 1);
			} else {
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = RelativeLayout.inflate(mContext,
						R.layout.carllist_item, null);
				holder = new ViewHolder();
				holder.card_name = (TextView) convertView
						.findViewById(R.id.card_name);
				holder.card_info = (TextView) convertView
						.findViewById(R.id.card_info);
				holder.card_distance = (TextView) convertView
						.findViewById(R.id.card_distance);
				holder.card_Phone=(TextView) convertView
						.findViewById(R.id.card_phone);
				holder.get_card = (Button) convertView
						.findViewById(R.id.get_card);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.card_name.setText(list.get(position).getName());
			holder.card_info
					.setText(list.get(position).getAddress());
			holder.card_distance.setText(list.get(position).getDistance()
					+ "km");
			if (null!=list.get(position).getPhone()) {
				holder.card_Phone.setText(list.get(position).getPhone());
			}
			holder.get_card.setTag(list.get(position).getStore_id());
			holder.get_card.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(NearbyCardActivity.this,
							CardInfoActivity.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intent.putExtra("store_id", v.getTag() + "");
					intent.putExtra("from","false");
					NearbyCardActivity.this.startActivity(intent);
				}
			});
			return convertView;
		}

		class ViewHolder {
			TextView card_name, card_info, card_distance,card_Phone;
			Button get_card;
		}

	

	}

	/**
	 * 设置相关参数
	 *//*
	private void setLocationOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setIsNeedAddress(true); // 返回的定位结果包含地址信息
		option.setAddrType("all"); // 返回的定位结果包含地址信息
		option.setCoorType("bd09ll"); // 返回的定位结果是百度经纬度,默认值gcj02
		option.setScanSpan(5000); // 设置发起定位请求的间隔时间为5000ms
		option.disableCache(true); // 禁止启用缓存定位
		option.setPoiNumber(5); // 最多返回POI个数
		option.setPoiDistance(1000); // poi查询距离
		option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
		mLocationClient.setLocOption(option);
	}
*/
//	public class MyLocationListener implements BDLocationListener {
//		@Override
//		public void onReceiveLocation(BDLocation location) {
//			if (location == null)
//				return;
//			StringBuffer sb = new StringBuffer(256);
//			sb.append("time : ");
//			sb.append(location.getTime());
//			sb.append("\nerror code : ");
//			sb.append(location.getLocType());
//			sb.append("\nlatitude : ");
//			sb.append(location.getLatitude());
//			sb.append("\nlontitude : ");
//			sb.append(location.getLongitude());
//			sb.append("\nradius : ");
//			sb.append(location.getRadius());
//			if (location.getLocType() == BDLocation.TypeGpsLocation) {
//				sb.append("\nspeed : ");
//				sb.append(location.getSpeed());
//				sb.append("\nsatellite : ");
//				sb.append(location.getSatelliteNumber());
//			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
//				sb.append("\naddr : ");
//				sb.append(location.getAddrStr());
//			}
//			// mText.setText(sb.toString());
//			
//			coordinate_x = Double.toString(location.getLongitude());
//			coordinate_y = Double.toString(location.getLatitude());
//			if (!coordinate_x.equals("")) {
//				if (isLocation) {
//					mLocationClient.stop();
//					getData();
//					isLocation=false;
//				}
//				
//			}else {
//				
//			}
//			
//
//			Log.d(TAG, "onReceiveLocation " + sb.toString());
//		}
//
//		public void onReceivePoi(BDLocation poiLocation) {
//			// 将在下个版本中去除poi功能
//			if (poiLocation == null) {
//				return;
//			}
//			StringBuffer sb = new StringBuffer(256);
//			sb.append("Poi time : ");
//			sb.append(poiLocation.getTime());
//			sb.append("\nerror code : ");
//			sb.append(poiLocation.getLocType());
//			sb.append("\nlatitude : ");
//			sb.append(poiLocation.getLatitude());
//			sb.append("\nlontitude : ");
//			sb.append(poiLocation.getLongitude());
//			sb.append("\nradius : ");
//			sb.append(poiLocation.getRadius());
//			if (poiLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
//				sb.append("\naddr : ");
//				sb.append(poiLocation.getAddrStr());
//			}
//			if (poiLocation.hasPoi()) {
//				sb.append("\nPoi:");
//				sb.append(poiLocation.getPoi());
//			} else {
//				sb.append("noPoi information");
//			}
//			// mTextPoi.setText(sb.toString());
//			
//			Log.d(TAG, "onReceiveLocation " + sb.toString());
//		}
//	}
	protected void showErrorView(boolean flag,String content){
		if (flag) {
			gone_layout.setVisibility(View.VISIBLE);
			card_list.setVisibility(View.GONE);
			if (!TextUtils.isEmpty(content)) {
				tv_error_text.setText(content);
			}
		}else {
			gone_layout.setVisibility(View.GONE);
			card_list.setVisibility(View.VISIBLE);
		}
	}
	//---------------------------------------------android 5.0 定位升级---------------------------------------------------
	private LocationUtils mLocationUtils;
	private void initLocation(){
		 mLocationUtils = LocationUtils.getInstance(getApplication());
		mLocationUtils.setLocationListener(new onLocationChangeListener() {
			
			@Override
			public void locationChange(BDLocation location) {
				coordinate_x = Double.toString(location.getLongitude());
				coordinate_y = Double.toString(location.getLatitude());
				if (!coordinate_x.equals("")) {
					if (isLocation) {
						
						getData();
						isLocation=false;
						mLocationUtils.stop();
					}
				}
			}
		});
		mLocationUtils.start();
	}
	
	
}
